<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
use Tymon\JWTAuth\Exceptions\JWTException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var string[]
     */
    protected $dontReport = [
        BusinessException::class
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var string[]
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $e)
    {
        if ($request->is('api/*')) {
            if ($e instanceof ValidationException) {
                $errors = $e->errors();
                $message = '';
                foreach ($errors as $val) {
                    $keys = array_key_first($val);
                    $message = $val[$keys];
                    break;
                }
                return response()->json(['code' => 40000, 'message' => $message, 'data' => []], 400);
            } elseif ($e instanceof JWTException) {
                return response()->json(['code' => 40001, 'message' => $e->getMessage(), 'data' => []], 401);
            } else if ($e instanceof NotFoundHttpException || $e instanceof MethodNotAllowedHttpException) {
                return response()->json(['code' => 404, 'message' => '请求资源不存在'], 404);
            } else if ($e instanceof BusinessException) {
                return response()->json(['code' => $e->getCode() ?: 40000, 'message' => $e->getMessage()], 400);
            } else {
                return response()->json(['code' => $e->getCode() ?: 500, 'message' => $e->getMessage() ?: '系统内部异常,稍后再试'], 500);
            }
        }

        return parent::render($request, $e);
    }
}
